<?php
include_once 'Singleton.php';

if(!defined("LOGIN_TIMEOUT")) define("LOGIN_TIMEOUT", 600);
if(!defined("SESSION_NAME")) define("SESSION_NAME", "mt_session");

/*
 * Class Session provides a simple interface to register a session for a user.
 */
 
class Session extends Singleton
{
  
  protected function Session()
  {
    if(!isset($_SESSION))
    {
      session_name(SESSION_NAME);
      session_start();  
    }  
  }
  
  private function updateTimeMark()
  {
    if(!isset($_SESSION['timeMark']))
    {
      $_SESSION['timeMark'] = time();
      return; 
    }
    
    if($this->isLogged() && time() - $_SESSION['timeMark'] < LOGIN_TIMEOUT)
    {
      $_SESSION['timeMark'] = time();
    }
    else
    {
      $_SESSION[expired] = time();
      $this->logout();
    }  
  }
  
  public static function &factory()
  {
    $s = parent::getSingleton(__CLASS__);
    
    if($s->isLogged())
    { 
      $s->updateTimeMark();
    }
    
    return $s;
  }
  
  public function login($fb_id)
  {
    $mysql = SQL::factory();
        
    $query = "SELECT id,fb_id FROM mt_user
              WHERE fb_id = '$fb_id'";
    
    $mysql->query($query);
    
    if($mysql->numRows() > 0)
    {
      if($mysql->numRows() > 1)
        throw MTException('More than one user with the same facebook id');
      
      $user = $mysql->query($query)->fetchObject(); 
      $_SESSION['userId'] = $user->id;
      $_SESSION['fbUserId'] = $user->fb_id;
      
      return true;
    }
    
    return false;
  }
  
  public function logout()
  {
    session_regenerate_id();
    
    unset($_SESSION['userId']);
    unset($_SESSION['timeMark']);
  }
  
  public function isLogged()
  {
    return isset($_SESSION["userId"]);
  }
   
  /*
  * use this function whenever you
  * need a session token to control
  * the flow of your operations (see registration for an example).
  * Note that using tokens prevents from brute force attack by bots.
  */
  
  public function generateToken(){
     $_SESSION[token] = bin2hex(md5(uniqid(rand(),1), true));
     return $_SESSION[token];
  }
  
  public function getUserId()
  {
    return $_SESSION['userId'];
  } 
  
  public function getFbUserId()
  {
    return $_SESSION['fbUserId'];
  } 
   
  public function getUserFbDetails()
  {
    return $_SESSION['fb_info'];
  } 
}

?>
